const app = getApp();

Component({
  data: {
    sizi_z: 1,
    ITEM_SIZE: 100, // 图片大小 单位px
    dragImgList: [], // 图片列表 { src: string, key: number, tranX: number, tranY: number }[]
    containerRes: {}, // 拖拽容器属性
    currentKey: -1, // 正在拖拽图片的key
    currentIndex: -1, // 正在拖拽图片的index
    tranX: 0, // 正在拖拽图片移动的x距离
    tranY: 0, // 正在拖拽图片移动的y距离
    uploadPosition: {
      // upload上传图标位移距离
      tranX: 0,
      tranY: 0,
    },
  },
  properties:{
    imgList: {
      type: Array,
      value: []
    },
  },
  lifetimes: {
    ready() {
      this.createSelectorQuery()
        .select(".drag-container")
        .boundingClientRect((res) => {
          this.data.containerRes = res;
        })
        .exec();
    },
  },

  methods: {
    /**
     * 长按图片
     */
    longPress(e) {
      const index = e.mark.index;
      console.log(index);
      const { pageX, pageY } = e.touches[0];
      const { top, left } = this.data.containerRes;
      this.setData({
        currentIndex: index,
        tranX: pageX - 50 - left,
        tranY: pageY - 50 - top,
      });
    },

    /**
     * touchMove
     */
    touchMove(e) {
      // 如果currentIndex < 0，说明并没有触发longPress
      if (this.data.currentIndex < 0) return;
      const { pageX, pageY } = e.touches[0];
      const { top, left } = this.data.containerRes;
      const tranX = pageX - 50 - left;
      const tranY = pageY - 50 - top;
      this.setData({
        tranX,
        tranY,
      });
      // 对比当前移动的key和停放位置的key，如果不一样就修改位置
      const currentKey = e.mark.key;
      const moveKey = this.getMoveKey(tranX, tranY);
      // console.log(currentKey, moveKey);container
      if (currentKey === moveKey || this.data.currentKey === currentKey) return;
      this.data.currentKey = currentKey;
      this.insert(currentKey, moveKey);
    },

    /**
     * 获取移动中的key
     */
    getMoveKey(tranX, tranY) {
      const { dragImgList: list, ITEM_SIZE } = this.data;
      const _getPositionNumber = (drag) => {
        const positionNumber = Math.round(drag / ITEM_SIZE);
        return positionNumber > 2 ? 2 : positionNumber < 0 ? 0 : positionNumber;
      };
      const endKey = 3 * _getPositionNumber(tranY) + _getPositionNumber(tranX);
      return endKey >= list.length ? list.length - 1 : endKey;
    },

    /**
     * 处理移动中key的变化
     */
    insert(origin, end) {
      const dragImgList = this.data.dragImgList;
      dragImgList.forEach((item) => {
        if (origin < end) {
          if (item.key > origin && item.key <= end) item.key--;
          else if (item.key === origin) item.key = end;
        } else if (origin > end) {
          if (item.key >= end && item.key < origin) item.key++;
          else if (item.key === origin) item.key = end;
        }
      });
      this.getListPosition(dragImgList);
    },

    /**
     * 修改位置
     */
    getListPosition(list) {
      const ITEM_SIZE = this.data.ITEM_SIZE;
      const dragImgList = list.map((item) => {
        item.tranX = ITEM_SIZE * (item.key % 3);
        item.tranY = Math.floor(item.key / 3) * ITEM_SIZE;
        return item;
      });
      this.setData({
        dragImgList,
      });

      const srcList = [...dragImgList]
        .sort((a, b) => a.key - b.key)
        .map((item) => item.src);
      this.triggerEvent("updateImage", {
        list: srcList,
      });
    },

    /**
     * touchEnd
     */
    touchEnd() {
      this.setData({
        tranX: 0,
        tranY: 0,
        currentIndex: -1,
      });
      this.data.currentKey = -1;
    },

    /**
     * 上传图片
     */
    uploadImage() {
      let { dragImgList, ITEM_SIZE } = this.data;
      wx.chooseImage({
        count: 9 - dragImgList.length,
        success: (res) => {
          const imgList = res.tempFilePaths.map((item, index) => ({
            tranX: ITEM_SIZE * ((dragImgList.length + index) % 3),
            tranY: Math.floor((dragImgList.length + index) / 3) * ITEM_SIZE,
            src: item,
            key: dragImgList.length + index,
          }));
          dragImgList = dragImgList.concat(imgList);
          this.setUploaPosition(dragImgList.length);
          this.setData({
            dragImgList,
            sizi_z: 2,
          });
        },
      });
    },

    /**
     * 修改上传图标位置
     */
    setUploaPosition(listLength) {
      const ITEM_SIZE = this.data.ITEM_SIZE;
      const uploadPosition = {
        tranX: (listLength % 3) * ITEM_SIZE,
        tranY: Math.floor(listLength / 3) * ITEM_SIZE,
      };
      this.setData({
        uploadPosition,
      });
    },

    /**
     * 删除图片
     */
    deleteImg(e) {
      const key = e.mark.key;
      const list = this.data.dragImgList.filter((item) => item.key !== key);
      list.forEach((item) => item.key > key && item.key--);
      this.getListPosition(list);
      this.setUploaPosition(list.length);
    },
    uploadFiles(fileType, isNeedThumbnail, canZero) {
      if (this.data.dragImgList.length == 0) {
        return new Promise(function (resolve, reject) {
          if (true == canZero) {
            resolve([]);
          } else {
            reject("请选择图片");
          }
        });
      } else {
        let ImgList = this.data.dragImgList;
        let promiseList = [];
        app.showLoading("提交中");
        let noUploadReq = [];
        ImgList.forEach((filePath) => {
          if (
            filePath.src.indexOf("tmp") != -1 ||
            filePath.src.indexOf("wxfile") != -1
          ) {
            promiseList.push(
              app.sHttp.upload({
                filePath: filePath.src,
                fileType: fileType,
                isNeedThumbnail: isNeedThumbnail,
              })
            );
          } else {
            noUploadReq.push(filePath);
          }
        });
        return new Promise(function (resolve, reject) {
          if (promiseList.length > 0) {
            Promise.all(promiseList)
              .then((result) => {
                noUploadReq.forEach((item) => {
                  result.push({
                    originalUrl: item,
                  });
                });
                wx.hideLoading();
                resolve(result);
              })
              .catch((error) => {
                wx.hideLoading();
                reject(error);
              });
          } else {
            wx.hideLoading();
            let result = [];
            noUploadReq.forEach((item) => {
              result.push({
                originalUrl: item,
              });
            });
            resolve(result);
          }
        });
      }
    },
  },
});
